Strings are fundamental data types in Python that represent sequences of characters. They are used to store text, including words, sentences, paragraphs, or any combination of characters.In Python, strings are immutable, meaning their contents cannot be changed after creation. If you need to modify a string, you'll create a new one with the desired changes.
Creating Strings
✦ You can create strings using single quotes ('), double quotes (""), or triple quotes (single ''' or double """).
✦ Single and double quotes are typically used for short, single-line strings.
✦ Triple quotes are useful for multiline strings or strings that contain single or double quotes within them.
Here are examples:
Basic examples to creating string in Python
# Single-line strings
name = 'Alice'
greeting = "Hello, world!"
# Multiline string with triple quotes
multiline_string ="""This is a string
that spans multiple lines."""
print(name,'\n',greeting,'\n',multiline_string)
Output
Alice
Hello, world!
This is a string
that spans multiple lines.
Initializing and Declaring Strings
Declaration
✦ In Python, declaration (or assignment) isn't strictly necessary. You create a variable by assigning a value to it.
✦ When you assign a string to a variable, you're essentially creating a ""name tag"" (the variable name) that refers to the string's memory location.
Initialization
✦ Initialization refers to assigning a value (in this case, a string) to a variable at the time of its creation. This is the common approach in Python.
Example:
Python string declaration example
message = 'Welcome to Python tutorial!'
print(message)
Output
Welcome to Python tutorial!
Explanation : Here, the variable message is initialized with the string value 'Welcome to Python tutorial!'.
Key Points
String contents are immutable (unchangeable)
✦ You can use various string methods to manipulate strings (e.g., concatenating, searching, replacing).
✦ Python automatically manages memory for strings.
Example
Example to understand python strings are immutable
name = "Bob"
age = 30
full_message = "Hello, " + name + "! You are " + str(age) + " years old."
print(full_message)
Output
Hello, Bob! You are 30 years old.
Explanation :
✦ name and age are initialized with string and integer values, respectively.
✦ full_message is created by concatenating strings and converting the integer age to a string using str().